﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using Think9.Models;
using Think9.Services.Basic;

namespace Think9.Controllers.Basic
{
    public class HomeController : BaseController
    {
        private UserService UserService = new UserService();
        private NotifyService NotifyService = new NotifyService();
        public IWebHostEnvironment WebHostEnvironment { get; set; }

        public override ActionResult Index(int? id)
        {
            ViewBag.Account = CurrentUser == null ? "" : CurrentUser.Account;
            ViewBag.HeadIcon = CurrentUser == null ? "" : CurrentUser.HeadIcon;
            return View(new WebEntity().GetWebInfo());
        }

        public ActionResult Main()
        {
            //DonationModel donationModel = DonationService.GetConsoleNumShow();
            //ViewBag.DonationTop = DonationService.GetSumPriceTop(5).ToList();
            return View();
        }

        public ActionResult UserInfo()
        {
            ViewBag.UploadFileSize = Think9.Services.Base.Configs.GetValue("UploadFileSize");
            ViewBag.UploadFileType = Think9.Services.Base.Configs.GetValue("UploadFileType");
            int userId = CurrentUser.UserId;
            var model = UserService.GetById(userId);
            return View(model);
        }

        /// <summary>
        /// 获取公告信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetNoticeList()
        {
            IEnumerable<dynamic> list = NotifyService.GetByWhere(null, null, null, "order by publishTime desc ");
            var result = new { code = 0, msg = "", count = 999999, data = list };
            return Json(list);
        }

        public ActionResult UserPwd()
        {
            ViewBag.UserName = CurrentUser.Account;
            return View();
        }

        public JsonResult ExportFile()
        {
            UploadFileEntity uploadFile = new UploadFileEntity();
            try
            {
                var file = Request.Form.Files[0];    //获取选中文件
                var filecombin = file.FileName.Split('.');
                if (file == null || string.IsNullOrEmpty(file.FileName) || file.Length == 0 || filecombin.Length < 2)
                {
                    uploadFile.code = -1;
                    uploadFile.src = "";
                    uploadFile.msg = "上传出错!请检查文件名或文件内容";
                    return Json(uploadFile);
                }
                //定义本地路径位置
                string localPath = WebHostEnvironment.WebRootPath + @"/Upload";
                string filePathName = string.Empty; //最终文件名
                filePathName = Think9.Util.Helper.Common.CreateNo() + "." + filecombin[1];
                //Upload不存在则创建文件夹
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                using (FileStream fs = System.IO.File.Create(Path.Combine(localPath, filePathName)))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                uploadFile.code = 0;
                uploadFile.src = Path.Combine("/Upload/", filePathName);
                uploadFile.msg = "上传成功";
                return Json(uploadFile);
            }
            catch (Exception)
            {
                uploadFile.code = -1;
                uploadFile.src = "";
                uploadFile.msg = "上传出错!程序异常";
                return Json(uploadFile);
            }
        }

        public ActionResult ExportFile2(List<IFormFile> file)
        {
            DataResult<string> rtnResult = new DataResult<string>();

            foreach (var formFile in file)
            {
                if (formFile.Length > 0)
                {
                    FileInfo fi = new FileInfo(formFile.FileName);
                    string ext = fi.Extension;
                    var orgFileName = fi.Name;
                    //var newFileName = Guid.NewGuid() + ext;
                    var newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + formFile.FileName;

                    var uploads = Path.Combine(Directory.GetCurrentDirectory(), "Resource");
                    var filePath = Path.Combine(uploads, newFileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        //await formFile.CopyToAsync(stream);
                    }
                    rtnResult.IsSuccess = true;
                }
                else
                {
                    rtnResult.ErrorMessage = "上传文件出错!";
                }
            }
            return Json(rtnResult);
        }
    }
}